﻿#region File Description
/*-----------------------------------------------------------------------------
 Author: Jose Antonio Gallego
 Date: 24/10/2011
 
 License: Ms-PL
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 The example companies, organizations, products, domain names,
 e-mail addresses, logos, people, places, and events depicted
 herein are fictitious.  No association with any real company,
 organization, product, domain name, email address, logo, person,
 places, or events is intended or should be inferred.
-----------------------------------------------------------------------------*/
#endregion

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using Zombsquare.Models;
using System.Device.Location;

namespace Zombsquare
{
    public partial class MapPage : INotifyPropertyChanged
    {
        #region Fields

        private Point _lastPoint;

        /// <value>Helper for handling visual states.</value>
        private readonly VisualStates _visualStates;

        private DispatcherTimer _DescriptionTimer;

        public static ObservableCollection<PushpinModel> Pushpins
        {
            get { return App.ViewModel.Pushpins; }
        }

        #endregion

        #region Ctor

        public MapPage()
        {
            this.Loaded += new RoutedEventHandler(MapPage_Loaded);
            
            LocalizacionHabilitada();

            InitializeDefaults();
            
            InitializeComponent();
            
            _visualStates = new VisualStates(this);

            _DescriptionTimer = new DispatcherTimer()
            {
                Interval = TimeSpan.FromSeconds(5.0)
            };

            _DescriptionTimer.Tick += new EventHandler(_DescriptionTimer_Tick);

            InitializeDataBase();

            InitializeGPS();

            DataContext = this;

            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                if (MessageBox.Show("Zombsquare necesita una conexión de datos para funcionar", "Conexión", MessageBoxButton.OK) == MessageBoxResult.OK)
                { 
                    //Esperar
                }

                throw new ApplicationNeedsToExitException();            
            }
        }

        void MapPage_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeDefaults();
        }

        private void LocalizacionHabilitada()
        {
            bool gps = true;

            System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<bool>("GPS", out gps);

            if (!gps)
            {
                if (MessageBox.Show("Esta aplicación utiliza los servicios de localización para mostrar su ubicación en el mapa. Este servicio es necesario para el correcto funcionamiento de la aplicación. Los datos de localización no serán almacenados ni enviados, solo se usan para localizarte en el mapa. ¿Desea permitir el acceso?", "Zombsquare", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["GPS"] = true;
                }
                else
                {
                    System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["GPS"] = false;
                    if (MessageBox.Show("Gracias por utilizar Zombsquare, la aplicación finalizara ahora.","",MessageBoxButton.OK)== MessageBoxResult.OK)
                    {
                       //Esperar
                    }

                    throw new ApplicationNeedsToExitException();
                }
            }
        }

        void _DescriptionTimer_Tick(object sender, EventArgs e)
        {            
            _visualStates.RouteState = VisualStates.HideRoute;
            _DescriptionTimer.Stop();
        }

        private void InitializeDataBase()
        {
            if (App.ViewModel.DataLoaded) return;
            App.ViewModel.LoadData();
        }

        #endregion

        #region Event Handlers

        private void ButtonLocation_Click(object sender, EventArgs e)
        {            
            _visualStates.PushpinsState = VisualStates.HidePushpins;
           
            CenterLocation();
        }

        private void ButtonRoute_Click(object sender, EventArgs e)
        {
            if (_visualStates.RouteState == VisualStates.HideRoute)
            {
                _visualStates.RouteState = VisualStates.ShowRoute;
            }
            else
            {
                _visualStates.RouteState = VisualStates.HideRoute;
            }

            // Hide pushpins panel.
            _visualStates.PushpinsState = VisualStates.HidePushpins;
        }

        private void ButtonMode_Click(object sender, EventArgs e)
        {
            ChangeMapMode();
            _visualStates.PushpinsState = VisualStates.HidePushpins;
        }

        private void GestureListener_Tap(object sender, GestureEventArgs e)
        {           
            _visualStates.PushpinsState = VisualStates.HidePushpins;
        }
                
        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            _lastPoint = e.GetPosition(Map);
            _visualStates.PushpinsState = VisualStates.HidePushpins;
        }

        private void GestureListener_Hold(object sender, GestureEventArgs e)
        {
            _lastPoint = e.GetPosition(Map);
            CenterPushpinsPopup(e.GetPosition(Map));
            _visualStates.PushpinsState = VisualStates.ShowPushpins;
        }

        private void ListBoxPushpinCatalog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = sender as Selector;
            if (selector == null || selector.SelectedItem == null)
            {
                return;
            }
            
            CreateNewPushpin(selector.SelectedItem, _lastPoint);

            selector.SelectedItem = null;

            _visualStates.PushpinsState = VisualStates.HidePushpins;
        }

        #endregion

        #region Property Changed

        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        #endregion

        #region Visual States
        /// <summary>
        /// An internal helper class for handling MainPage visual state transitions.
        /// </summary>
        private class VisualStates
        {
            #region Predefined Visual States
            // Route States
            public const string ShowRoute = "ShowRoute";
            public const string HideRoute = "HideRoute";

            // Directions States
            public const string ShowDirections = "ShowDirections";
            public const string HideDirections = "HideDirections";

            // Pushpins States
            public const string ShowPushpins = "ShowPushpins";
            public const string HidePushpins = "HidePushpins";
            #endregion

            #region Fields
            private readonly Control _control;
            private string _routeState = VisualStates.HideRoute;
            private string _directionsState = VisualStates.HideDirections;
            private string _pushpinsState = VisualStates.HidePushpins;
            #endregion

            #region Properties
            /// <summary>
            /// Change the route panel visual state.
            /// </summary>
            public string RouteState
            {
                get { return _routeState; }
                set
                {
                    if (_routeState != value)
                    {
                        _routeState = value;
                        VisualStateManager.GoToState(_control, value, true);
                    }
                }
            }

            /// <summary>
            /// Change the directions panel visual state.
            /// </summary>
            public string DirectionsState
            {
                get { return _directionsState; }
                set
                {
                    if (_directionsState != value)
                    {
                        _directionsState = value;
                        VisualStateManager.GoToState(_control, value, true);
                    }
                }
            }

            /// <summary>
            /// Change the pushpins popup visual state.
            /// </summary>
            public string PushpinsState
            {
                get { return _pushpinsState; }
                set
                {
                    if (_pushpinsState != value)
                    {
                        _pushpinsState = value;
                        VisualStateManager.GoToState(_control, value, true);
                    }
                }
            }
            #endregion

            #region Ctor
            /// <summary>
            /// Initializes a new instance of this class.
            /// </summary>
            /// <param name="control">The target control.</param>
            public VisualStates(Control control)
            {
                _control = control;
            }
            #endregion
        }
        #endregion
    }
}
